package cn.ipenta.jkb.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.ipenta.jkb.utils.JsonMapper;

@ControllerAdvice
public class GlobalExceptionHandler {

	private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

	@ExceptionHandler(Exception.class)
	public @ResponseBody Map<String, Object> jsonErrorHandler(Exception e) throws Exception {
		logger.error("[GlobalExceptionHandler]:" + e.getMessage());
		return JsonMapper.fail(e.getMessage());
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public @ResponseBody Map<String, Object> handleConstraintViolationException(MethodArgumentNotValidException e) {
		List<ObjectError> errors = e.getBindingResult().getAllErrors();
		Map<String, List<String>> errerMap = new HashMap<>();
		List<String> errers = new ArrayList<>();
		for (ObjectError objectError : errors) {
			errers.add(objectError.getDefaultMessage());
		}
		errerMap.put("inputerrors", errers);

		return JsonMapper.fail(errerMap);
	}

}